import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
// import { MessageBox, Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (config.method === 'post') {
      if (config.url === '/dev-api/api/v1/common/upload') {
        config.headers['Content-Type'] = 'multipart/form-data'
      } else {
        config.headers['Content-Type'] = 'application/json'
      }
    }

    // do something before request is sent
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
      // config.headers['Authorization']
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    if (res.code === 200) {
      return response
    }
    console.log(response)
  },
  error => {
    // console.log('hello error')
    const res = error.response.data
    if (error.response.status >= 500) {
      Message({
        showClose: true,
        message: '服务器繁忙暂时无法响应服务，请稍候。',
        duration: 3000,
        type: 'error'
      })
    }
    // console.log(error.response.data)
    if (error.response.status >= 400 && error.response.status < 500) {
      if (res.msg !== undefined && res.msg !== null && res.msg !== '') {
        Message({
          showClose: true,
          message: res.msg,
          duration: 3000,
          type: 'warning'
        })
        return res
      } else {
        return error
      }
    }
  }
)

export default service
